package com.scut.campus.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * transactionTemplate config
 *
 * @author zhaowen.jian
 * @version TransactionTemplateConfig.java v1.0 2022-04-28 10:42 上午
 */
@Configuration
public class TransactionTemplateConfig {

    @Autowired
    private PlatformTransactionManager transactionManager;

    /**
     * default timeout
     */
    @Value("${bizf.transaction.template.default.timeout:3}")
    private int timeout;

    /**
     * 默认事务模板，传播特性为REQUIRED
     *
     * @return TransactionTemplate
     */
    @Bean(name = "transactionTemplate")
    public TransactionTemplate transactionTemplate() {
        final TransactionTemplate t = new TransactionTemplate(transactionManager);
        t.setTimeout(timeout);
        return t;
    }

    /**
     * REQUIRES_NEW专用事务模板，传播特性为REQUIRES_NEW
     *
     * @return TransactionTemplate
     */
    @Bean(name = "transactionTemplateRequiresNew")
    public TransactionTemplate transactionTemplateRequiresNew() {
        final TransactionTemplate t = new TransactionTemplate(transactionManager);
        t.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        t.setTimeout(timeout);
        return t;
    }

    /**
     * bizf mq transaction template
     *
     * @return transaction template
     */
    @Bean(name = "bizfMqTransactionTemplate")
    public TransactionTemplate bizfMqTransactionTemplate() {
        return new TransactionTemplate(transactionManager);
    }

    /**
     * bizf mq transaction template
     *
     * @return transaction template
     */
    @Bean(name = "bizfMqTransactionTemplateRequiresNew")
    public TransactionTemplate bizfMqTransactionTemplateRequiresNew() {
        final TransactionTemplate t = new TransactionTemplate(transactionManager);
        t.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        return t;
    }
}
